package com.codingchili.logging.configuration;

import io.vertx.core.Future;
import io.vertx.core.Promise;

import com.codingchili.core.context.*;
import com.codingchili.core.security.Token;
import com.codingchili.core.security.TokenFactory;
import com.codingchili.core.storage.*;

/**
 * @author Robin Duda
 * <p>
 * Context used by logging handlers.
 */
public class LogContext extends SystemContext implements ServiceContext {
    private final TokenFactory clientFactory;
    private final TokenFactory serverFactory;

    public LogContext(CoreContext context) {
        super(context);
        clientFactory = new TokenFactory(this, service().getClientSecret());
        serverFactory = new TokenFactory(this, service().getLoggingSecret());
    }

    public Future<AsyncStorage<JsonStorable>> storage(String collection) {
        var promise = Promise.<AsyncStorage<JsonStorable>>promise();
        if (storageEnabled()) {
            new StorageLoader<JsonStorable>(this)
                    .withPlugin(service().getPlugin())
                    .withValue(JsonStorable.class)
                    .withDB(service().getDb())
                    .withCollection(collection)
                    .withProperties(service().getElastic())
                    .build(result -> {
                        if (result.succeeded()) {
                            promise.complete(result.result());
                        } else {
                            promise.fail(result.cause());
                        }
                    });
        } else {
            promise.complete();
        }
        return promise.future();
    }

    public LogServerSettings service() {
        return LogServerSettings.get();
    }

    public boolean consoleEnabled() {
        return service().getConsole();
    }

    public boolean storageEnabled() {
        return service().getStorage();
    }

    public Future<Void> verifyClientToken(Token token) {
        return clientFactory.verify(token);
    }

    public Future<Void> verifyServerToken(Token token) {
        return serverFactory.verify(token);
    }
}
